package com.autumn.juc.jmm;

import com.autumn.juc.lock.CASLock;

public class Test {
    //保证有序性和可见性，无法保证原子性
    private volatile static int sum = 0;
    //static Object object = "";
    //static ReentrantLock lock = new ReentrantLock();

    static CASLock casLock = new CASLock();

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(() -> {
                //synchronized (object) {
                //lock.lock();
                //自旋，即空转，若长时间空转会给CPU带来非常大的开销
                for (; ; ) {
                    //state=0
                    if (casLock.getState() == 0 && casLock.cas()) {
                        //状态为0时可以抢锁，抢到时，cas方法将状态改为1，其他线程无法抢锁进行自旋
                        try {
                            for (int j = 0; j < 10000; j++) {
                                sum++;
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            //    lock.unlock();
                            //state=0，线程执行完毕之后状态改回来，其他自旋中的线程重新抢锁
                            casLock.setState(0);
                        }
                        break;
                    }
                }
            });
            thread.start();
        }
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(sum);
    }
}
